import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/home/news_detail_logic.dart';
import 'package:sports_new/entity/home/news_item_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/home_api.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/home/report_sheet.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/picture_preview_widget.dart';

import '../../widgets/base/qkd_text.dart';

class PostCell extends StatefulWidget {
  final NewsItemEntity data;
  //0 列表 1详情
  final int type;
  final bool isUserPage;
  final void Function()? afterRoute;
  const PostCell(this.data,
      {super.key, this.type = 0, this.afterRoute, this.isUserPage = false});

  @override
  State<PostCell> createState() => _PostCellState();
}

class _PostCellState extends State<PostCell> {
  late NewsItemEntity data;
  late int type;
  late List<String> images;
  late NewsDetailLogic logic;

  @override
  void initState() {
    super.initState();
    data = widget.data;
    type = widget.type;
    // logic = Get.find<NewsDetailLogic>(tag: '${data.id}');
    images = (data.imgs.hasValue ? data.imgs!.split(',') : []);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        await Get.toNamed(Routes.homenews, arguments: data.id);
        widget.afterRoute?.call();
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: type == 0 ? 12 : 16),
        margin: EdgeInsets.only(
            left: type == 0 ? 8 : 0,
            right: type == 0 ? 8 : 0,
            top: type == 0 ? 8 : 0),
        decoration: BoxDecoration(
            color: Colours.white, borderRadius: BorderRadius.circular(8)),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          SizedBox(height: type == 0 ? 12 : 16),
          Row(
            children: [
              userWidget(),
              const Spacer(),
              if (!widget.isUserPage)
                FocusButton(
                  data.focus ?? 0,
                  userId: data.publisherId,
                  type: type == 1 ? 0 : 1,
                  onTap: (p0) {},
                )
            ],
          ),
          contentWidget(),
          if (images.isNotEmpty)
            Container(margin: const EdgeInsets.only(top: 8), child: imageWidget()),
          if (data.commentRecord != null)
            Container(margin: const EdgeInsets.only(top: 8), child: hotComment()),
          bottom()
        ]),
      ),
    );
  }

  Widget userWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        Get.toNamed(Routes.userPage,
            arguments: data.publisherId, parameters: {'type': '1'});
      },
      child: Row(
        children: [
          ClipOval(
            child: CachedNetworkImage(
              imageUrl: data.logo ?? '',
              width: 40,
              height: 40,
              fit: BoxFit.cover,
              placeholder: (context, url) => Container(),
            )
          ),
          const SizedBox(width: 8),
          Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            QkdText(data.publisherName ?? '',
              fontWeight: FontWeight.w500
            ),
            QkdText(data.publishTime ?? '',
              color: Colours.grey99, fontSize: 12
            )
          ]),
        ],
      ),
    );
  }

  Widget contentWidget() {
    String content = (type == 1 ? data.content : data.summary) ?? '';
    if (content.hasValue == false) {
      content = '分享图片';
    }
    return Container(
      margin: const EdgeInsets.only(top: 8),
      child: Text.rich(
        TextSpan(children: [
          if (data.top == 1 && type == 0)
            WidgetSpan(
                alignment: PlaceholderAlignment.middle,
                child: Container(
                  width: 24,
                  height: 14,
                  alignment: Alignment.center,
                  // padding: const EdgeInsets.symmetric(horizontal: 2,vertical: 1),
                  margin: const EdgeInsets.only(right: 5),
                  decoration: BoxDecoration(
                      border: Border.all(width: 0.5, color: Colours.main),
                      borderRadius: BorderRadius.circular(3)),
                  child: QkdText(
                    "置顶",
                    needCenter: true,
                    color: Colours.main, fontSize: 10,
                  ),
                )),
          TextSpan(
            text: content,
            style: const TextStyle(color: Colours.text, fontSize: 16),
          )
        ]),
        maxLines: type == 0 ? 2 : null,
        overflow: type == 0 ? TextOverflow.ellipsis : null,
        textAlign: TextAlign.left,
      ),
    );
  }

  Widget imageWidget() {
    double postWidth = Get.width - (type == 0 ? 40 : 32);
    if (images.length == 1) {
      double? width = postWidth;
      double? height = width / 2;
      if (data.imgRatio.hasValue) {
        double ratio = double.parse(data.imgRatio!.split(',').first);
        if (ratio >= 1.5) {
          width = postWidth / 3 * 2;
          height = width / 2;
        } else if (ratio <= 0.84) {
          width = postWidth / 2;
          height = width / 0.84;
        } else {
          return ConstrainedBox(
              constraints: BoxConstraints(maxWidth: postWidth / 3 * 2),
              child: AspectRatio(
                aspectRatio: ratio,
                child: image(index: 0),
              ));
        }
      }
      return image(
        index: 0,
        width: width,
        height: height,
      );
    } else {
      int maxImage = type == 0 ? 3 : 9;
      double size = (Get.width - (type == 0 ? 56 : 48) - 1) / 3;
      return Wrap(
          spacing: 8,
          runSpacing: 8,
          children: List.generate(
              images.length > maxImage ? maxImage : images.length,
              (index) => image(index: index, width: size, height: size)));
    }
  }

  Widget image({required int index, double? width, double? height}) {
    final url = images[index];
    return GestureDetector(
      onTap: () {
        Get.dialog(
            PicturePreview(
              imageUrlArray: images,
              initialIndex: index,
            ),
            useSafeArea: false);
        // Get.dialog(PicturePreview(imageUrl: url ?? ""), useSafeArea: false);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: CachedNetworkImage(
          imageUrl: url,
          width: width,
          height: height,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget hotComment() {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
          color: Colours.greyF5F7FA, borderRadius: BorderRadius.circular(8)),
      child: Text.rich(TextSpan(children: [
        WidgetSpan(
            child: Image.asset(Utils.getImgPath('hot_comment.png'),
                width: 30, height: 20)),
        const WidgetSpan(child: SizedBox(width: 4)),
        TextSpan(
            text: data.commentRecord!.comment,
            style: const TextStyle(fontSize: 15, color: Colours.text))
      ])),
    );
  }

  Widget bottom() {
    return type == 0 ? cellBottom() : detailBottom();
  }

  detailBottom() {
    return Padding(
        padding: const EdgeInsets.symmetric(vertical: 30),
        child: GestureDetector(
          onTap: onZan,
          child: Align(
            child: Container(
              width: 68,
              height: 68,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(34),
                  border: Border.all(color: Colours.main),
                  color: data.isLike == 0 ? Colours.white : Colours.main),
              child: Column(children: [
                const SizedBox(height: 16),
                Image.asset(
                  Utils.getImgPath(
                      data.isLike == 0 ? 'zan_big.png' : 'zan_big1.png'),
                  width: 28,
                ),
                const SizedBox(height: 2),
                QkdText(
                  '${data.likeNum}',
                  color: data.isLike == 1 ? Colours.white : Colours.main,
                  fontSize: 12,
                )
              ]),
            ),
          ),
        ));
  }

  cellBottom() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(children: [
        if (data.h5url.hasValue)
          GestureDetector(
            onTap: () {
              Clipboard.setData(ClipboardData(text: data.h5url ?? ''))
                  .then((value) => ToastUtils.show("已复制分享链接"));
            },
            child: Row(
              children: [
                Image.asset(
                  Utils.getImgPath('news_share.png'),
                  width: 20,
                ),
                const SizedBox(width: 4),
                const SizedBox(
                  width: 40,
                  child: QkdText('分享', fontSize: 13)
                )
              ],
            ),
          ).marginOnly(right: 20),
        GestureDetector(
          child: Row(
            children: [
              Image.asset(
                Utils.getImgPath('comment.png'),
                width: 20,
              ),
              const SizedBox(width: 4),
              SizedBox(
                width: 40,
                child: QkdText(
                  data.commentNum.hasValue ? '${data.commentNum}' : '评论',
                  fontSize: 13
                )
              )
            ],
          ),
        ),
        const SizedBox(width: 20),
        GestureDetector(
          onTap: onZan,
          child: Row(
            children: [
              Image.asset(
                Utils.getImgPath(data.isLike == 1 ? 'zan_red.png' : 'zan.png'),
                width: 20,
              ),
              const SizedBox(width: 4),
              SizedBox(
                width: 40,
                child: QkdText(data.likeNum.hasValue ? '${data.likeNum}' : '点赞',
                  fontSize: 13,
                  color:
                  data.isLike == 1 ? Colours.main : Colours.text
                )
              )
            ],
          ),
        ),
        const Spacer(),
        GestureDetector(
          onTap: () {
            ReportSheet.reportPost(data.id!);
          },
          behavior: HitTestBehavior.opaque,
          child: Container(
              width: 20,
              height: 20,
              alignment: Alignment.bottomRight,
              child:
                  Image.asset(Utils.getImgPath('post_close.png'), width: 10)),
        )
      ]),
    );
  }

  onZan() async {
    if (data.isLike == 1) {
      final result = await HomeApi.newsSupport(data.id!, type: 4);
      if (result == 200) {
        data.isLike = 0;
        data.likeNum = data.likeNum! - 1;
        ToastUtils.show("已取消点赞");
      }
    } else {
      final result = await HomeApi.newsSupport(data.id!, type: 2);
      if (result == 200) {
        data.isLike = 1;
        data.likeNum = data.likeNum! + 1;
        ToastUtils.show("点赞成功");
      }
    }
    if (type == 1) {
      final logic = Get.find<NewsDetailLogic>(tag: '${data.id}');
      logic.update();
    } else {
      update();
    }
    // update();
  }
}
